<?php
/**
 * Created by PhpStorm.
 * User: haohao
 * Date: 2021/12/31
 * Time: 16:32
 */

namespace App\Admin\Metrics;

use App\Models\OrderModel;
use App\Models\UserModel;
use  Dcat\Admin\Admin;
use Dcat\Admin\Widgets\ApexCharts\Chart;
use Illuminate\Support\Carbon;

class UserAdd extends Chart {
    public function __construct($containerSelector = null, $options = [])
    {
        parent::__construct($containerSelector, $options);

        $this->setUpOptions();
    }

    /**
     * 初始化图表配置
     */
    protected function setUpOptions()
    {
        $color = Admin::color();
        $this->title('用户增长趋势');
        $colors = [$color->primary(), $color->primaryDarker()];

        $this->options([
            'colors' => $colors,
            'chart' => [
                'type' => 'bar',
                'height' => 430
            ],
            'plotOptions' => [
                'bar' => [
                    'horizontal' => false,
                    'dataLabels' => [
                        'position' => 'top',
                    ],
                ]
            ],
            'dataLabels' => [
                'enabled' => true,
                'offsetX' => 0,
                'style' => [
                    'fontSize' => '12px',
                    'colors' => ['#fff']
                ],
            ],
            'stroke' => [
                'show' => true,
                'width' => 1,
                'colors' => ['#fff']
            ],
            'xaxis' => [
                'categories' => [],
            ],
        ]);
    }

    /**
     * 处理图表数据
     */
    protected function buildData()
    {
//        // 执行你的数据查询逻辑
        $user7 = UserModel::query()
            ->selectRaw('date(created_at) as date, count(*) as total')
            ->whereBetween('created_at', [Carbon::today()->subDays(30), Carbon::tomorrow()])
            ->groupBy('date')
            ->get()
            ->toArray();
//        $last_names = array_column($user7,'date');
//        array_multisort($last_names,SORT_DESC,$last_names);
        $user7 = $this->order_date_array($user7,'desc','date');
        $date = [];
        $total = [];
        for ($i=count($user7);$i--;){
            $date[] = $user7[$i]['date'];
            $total[] = $user7[$i]['total'];
        }
        $data = [
            [
                'data' => $total
            ]
        ];
        $categories = $date;

        $this->withData($data);
        $this->withCategories($categories);
    }
    /*
     * 将二维数组按日期（支持Ymd和Ynj格式日期）排序
     * order_date_array(原始二维数组, desc还是asc, 日期在二维数组中的键)
     * */
    function order_date_array($array, $order, $key){

    if (!$array){
        return [];
    }else{
        $_array = $array;
    }

    if (!$order){
        $_order = 'desc';
    }else{
        $_order = $order;
    }

    if (!$key){ // 二维数据中的Ynj日期的键
        $_key = 'date';
    }else{
        $_key = $key;
    }

    $new_array = [];
    $array_1 = [];
    $array_2 = [];

    // 日期转时间戳
    for ($t=0; $t<count($_array); $t++){
        $date = strtotime($_array[$t][$_key]); // Ymd或者Ynj格式日期转时间戳
        $array_1[] = $date;
        $array_2[] = $date;
    }
    // 排列方式
    if ($_order === 'desc'){ // 降序
        rsort($array_2);
    }else{ // 升序
        sort($array_2);
    }
    // 重新排序原始数组
    for ($r=0; $r<count($array_2); $r++){

        $index = array_search($array_2[$r], $array_1); // 元素索引
        $new_array[] = $_array[$index];
    }

    return $new_array;
}
    /**
     * 设置图表数据
     *
     * @param array $data
     *
     * @return $this
     */
    public function withData(array $data)
    {
        return $this->option('series', $data);
    }

    /**
     * 设置图表类别.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withCategories(array $data)
    {
        return $this->option('xaxis.categories', $data);
    }

    /**
     * 渲染图表
     *
     * @return string
     */
    public function render()
    {
        $this->buildData();

        return parent::render();
    }
}
